<template>
  <div>
    <p-input
      placeholder="Basic usage"
      v-model="value"
      read-only
      @change="onChangeMaterialNo"
      ref="userNameInput"
      @click="openPop"
      :disabled="disabled"
    >
      <p-icon slot="prefix" type="cluster" />
    </p-input>
    <p-modal
      title="请选择"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭"
      width="70%"
    >

      <p-row :gutter="24" v-if="oNswitch">
        穿梭框
        <p-switch @change="switchonChange" />
      </p-row>

      <ong-select-list
        v-show="switchs"
        v-if="onlyField"
        :recode="reportCode"
        :add="this.add"
        :context="context"
        :listaip="this.listaip"
        :mainTableID="this.mainTableID"
        :destFields="this.destFields"
        :orgFields="this.orgFields"
        :onlyField="this.onlyField"
        @oNvisible="oNvisible"
        ref="fxPopupSelect"
        style="margin-top:10px"></ong-select-list>
      <ong-list
        v-show="!switchs"
        :recode="reportCode"
        :isMultiSelect="isMultiSelect"
        :context="context"
        :tableColumns="tableColumns"
        @callback="callbackMid"
        ref="fxFlieRef"></ong-list>
    </p-modal>
  </div>
</template>
<script>
 import Vue from 'vue'
  import { getColumns, getData, getQueryInfo } from '@/api/api'
  import { httpAction } from '@/api/manage'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ongList from './modules/OnlCgreportAutoList'
  import ongSelectList from './modules/OnlCgreportAutoSelectList'
  export default {
    name: 'FPopupMes',
    components: {
      ongList,
      ongSelectList
    },
    props: {
      value: {
        type: String,
        required: false
      },
      contextPath: {
        type: String,
        default: ''
      },
      tdId: {
        type: String,
        default: '0'
      },
      code: {
        type: String,
        default: ''
      },
      orgFields: {
        type: String,
        default: []
      },
      destFields: {
        type: String,
        default: []
      },
      disabled: {
        type: Boolean,
        default: false
      },
      multiple: {
        type: Boolean,
        default: false
      },
      // 是否多选
      // popup_multi
      isMultiSelect: {
        type: String,
        default: 'popup'
      },
      // 添加的aip
      add: {
        type: String,
        default: ''
      },
      // 列表的aip
      listaip: {
        type: String,
        default: ''
      },
      // 主表id
      mainTableID: {
        type: Object,
        default: function () {
          return {}
        }
      },
      // 唯一字段
      onlyField: {
        type: String,
        default: ''
      },
      tableColumns: {
        type: Array,
        default:[]
      }
    },
    data () {
      return {
        refShow: false,
        visible: false,
        listVisble: false,
        confirmLoading: false,
        userName: 'username',
        codeStr: this.code,
        context: this.contextPath === '' ? '' : '/' + this.contextPath,
        reportCode: '',
        list: [],
        orgField: this.getList(this.orgFields),
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        selectionId: '0',
        selectedRowKeys: [],
        selectionRows: [],
        toggleSearchStatus: false,
        switchs: false,

      }
    },
    watch: {
      orgFields: {
        deep: true,
        handler (val) {
          this.orgField = this.getList(val)
        }
      }
    },
    computed: {
      // eslint-disable-next-line vue/return-in-computed-property
      oNswitch: function () {
        if (this.value == undefined && this.onlyField) {
          return true
        } else {
          // eslint-disable-next-line vue/no-side-effects-in-computed-properties
          this.switchs = false
        }
      },
    },
    created () {
      const vm = this
      getColumns(vm.context, vm.codeStr).then(res => {
        if (res.success) {
          vm.columns = res.data.columns
          vm.reportCode = res.data.cgRpConfigId
        }
      })
    },
    methods: {
      switchonChange (checked) {
         this.switchs = checked
      },
      getList (val) {
        let array = []
        array = val.split(',')
        return array
      },
      onChangeMaterialNo (e) {
      },
      openPop () {
        const vm = this.orgField
        this.visible = true
        this.refShow ? this.$refs.fxFlieRef.setTableRow() : ''
        this.refShow && this.onlyField ? this.$refs.fxPopupSelect.getList() : ''
        this.refShow = true
        for (let i = 0; i < vm.length; i++) {
          this.list.push({
            label: vm[i],
            value: vm[i]
          })
        }
      },
      onSelectChange (selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },
      onSelect (record, selected) {
        if (selected == true) {
          this.selectionRows.push(record)
        } else {
          this.selectionRows.forEach(function (item, index, arr) {
            if (item.id == record.id) {
              arr.splice(index, 1)
            }
          })
        }
      },
      changeList (index) {
        index === 0 ? (this.listVisble = true) : index
      },
      toHump (name) {
        return name.replace(/\_(\w)/g, function (all, letter) {
          return letter.toUpperCase()
        })
      },
      sort (obj) {
         var objs = {}
         const arr = this.orgFields.split(',')
         // 转换key
         arr.forEach((items, indexs) => {
           for (var i in obj) {
              if (i == items) {
                objs[i] = obj[i]
              }
          };
         })
          const newSelectionRows = []
          const param = {} // 新生成一个新的数组出来,来保存需要过滤的数据
          var keyMap = {}
          this.destFields.split(',').forEach((item, index) => {
            newSelectionRows.push(this.toHump(item))
          })
          arr.forEach((item, index) => {
            if (objs[item] != undefined) {
              param[item] = objs[item].toString()
            }
            keyMap[item] = newSelectionRows[index]
          })
          for (var key in param) {
            var newKey = keyMap[key]
            if (newKey) {
              if (param[newKey] !== param[key]) {
                param[newKey] = param[key]
                delete param[key]
              }
            }
          }
         return param
      },
      extend (target, source) {
        for (var p in source) {
            if (source.hasOwnProperty(p)) {
                target[p] = source[p]
            }
        }
        return target
      },
      addData (data) {
        // 转换
        const newData = []
          var m = {}
          data.forEach((item, index) => {
            for (const i in item) {
              if (!this.orgFields.split(',').includes(i)) {
                delete item[i]
              }
            }
            newData.push(this.sort(item))
          })
          newData.forEach((item, index) => {
            if (this.mainTableID) {
               m = this.extend(item, this.mainTableID)
               console.log(m)
            } else {
              m = item
            }
            httpAction(this.add, m, 'post').then((res) => {
              if (res.success) {
                  if (newData.length - 1 == index) {
                    this.visible = false
                    this.$emit('oNvisible')
                  }
              } else {
                this.$message.warning(res.msg)
              }
            })
          })
      },
      handleOk () {
        // 穿梭
        if (this.switchs) {
          const filterKey = []
          this.$refs.fxPopupSelect.targetKeys.filter(item => {
            if (!this.$refs.fxPopupSelect.dataKeys.includes(item)) {
              filterKey.push(item)
            }
          })
          if (filterKey.length == 0) {
            this.visible = false
            return false
          }
          this.$refs.fxPopupSelect.loadingTable = true
          const newarr = this.$refs.fxPopupSelect.mockData.filter(item => {
            // if (this.$refs.fxPopupSelect.targetKeys.includes(item.key)) {
            if (filterKey.includes(item.key)) {
              return true
            }
          })
          const newRemovet = []
          var m = {}
          newarr.forEach((item, index) => {
            for (const i in item) {
              if (!this.orgFields.split(',').includes(i)) {
                delete item[i]
              }
            }
            newRemovet.push(this.sort(item))
          })
          newRemovet.forEach((itemd, index) => {
            if (this.mainTableID) {
               m = this.extend(itemd, this.mainTableID)
            } else {
              m = itemd
            }
            httpAction(this.add, m, 'post').then((res) => {
              if (res.success) {
                  if (newRemovet.length - 1 == index) {
                    this.$refs.fxPopupSelect.loadingTable = false
                    this.visible = false
                    this.$emit('oNvisible')
                  }
              } else {
                this.$refs.fxPopupSelect.loadingTable = false
                this.$message.warning(res.msg)
              }
            })
          })
          return false
        }
        if (this.isMultiSelect == 'popup_multi') {
          // 多选
          this.visible = false
          if(this.selectionRows.length == 1){
            const arr = this.orgFields.split(',')
            const newSelectionRows = []
            const param = {} // 新生成一个新的数组出来,来保存需要过滤的数据
            var keyMap = {}
            this.destFields.split(',').forEach((item, index) => {
              newSelectionRows.push(this.toHump(item))
            })
            arr.forEach((item, index) => {
              if (this.selectionRows[0][item] != undefined) {
                param[item] = this.selectionRows[0][item].toString()
              }
              keyMap[item] = newSelectionRows[index]
            })
            for (var key in param) {
              var newKey = keyMap[key]
              if (newKey) {
                if (param[newKey] !== param[key]) {
                  param[newKey] = param[key]
                  delete param[key]
                }
              }
            }
            this.$emit('callback', param)
            this.$emit('input', this.selectionId, param)
            this.handleCancel()
            this.selectedRowKeys = []
            this.selectionRows = []
            return false
          }
          this.addData( this.selectionRows)
          this.handleCancel()
          this.selectedRowKeys = []
          this.selectionRows = []
        } else if (this.isMultiSelect == 'popup') {
          // 单选
          this.visible = false
          const arr = this.orgFields.split(',')
          const newSelectionRows = []
          const param = {} // 新生成一个新的数组出来,来保存需要过滤的数据
          var keyMap = {}
          this.destFields.split(',').forEach((item, index) => {
            newSelectionRows.push(this.toHump(item))
          })
          arr.forEach((item, index) => {
            if (this.selectionRows[item] != undefined) {
              param[item] = this.selectionRows[item].toString()
            }
            keyMap[item] = newSelectionRows[index]
          })
          for (var key in param) {
            var newKey = keyMap[key]
            if (newKey) {
              if (param[newKey] !== param[key]) {
                param[newKey] = param[key]
                delete param[key]
              }
            }
          }
          this.$emit('callback', param)
          this.$emit('input', this.selectionId, param)
          this.handleCancel()
          this.selectedRowKeys = []
          this.selectionRows = []
        }
      },
      callbackMid (row) {
        const that = this
        if (this.isMultiSelect == 'popup_multi') {
          this.selectionId = this.value
          this.selectionRows = row
        } else {
          this.selectionId = this.value
          this.selectionRows = row
        }
      },
      handleCancel () {
        this.visible = false
        this.list = []
      },
      shutdown () {
        this.listVisble = false
      }
    },
    mounted () {}
  }
</script>

<style lang="less" scoped></style>
